package cn.kgc.crowdfundingadmin.service;

import cn.kgc.crowdfundingadmin.common.CrowdFundingUtils;
import cn.kgc.crowdfundingadmin.mapper.AdminMapper;
import cn.kgc.crowdfundingadmin.mapper.AuthMapper;
import cn.kgc.crowdfundingadmin.mapper.RoleMapper;
import cn.kgc.crowdfundingadmin.pojo.*;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class CrowdUserDetailsService implements UserDetailsService {
    @Resource
    AdminMapper adminMapper;

    @Resource
    RoleMapper roleMapper;

    @Resource
    AuthMapper authMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        AdminExample example=new AdminExample();
        AdminExample.Criteria criteria = example.createCriteria();
        criteria.andLoginacctEqualTo(s);
        List<Admin> admins=adminMapper.selectByExample(example);
        if(CrowdFundingUtils.collectionEffective(admins)) {
            Admin admin = admins.get(0);

            //封装角色和权限的集合
            List<GrantedAuthority> authorityList=new ArrayList<>();

            //获取角色对象
            List<Role> roleList=roleMapper.getAssignedRoleList(admin.getId());
            //存储角色id,用于权限查询
            List<Integer> authIdList=new ArrayList<>();
            if(CrowdFundingUtils.collectionEffective(roleList)){
                for (Role role : roleList) {
                    authorityList.add(new SimpleGrantedAuthority("ROLE_"+role.getName()));
                    authIdList.add(role.getId());
                }
            }
            //存储权限
            List<Auth> authList=authMapper.selectByRoleIds(authIdList);
            if(CrowdFundingUtils.collectionEffective(authIdList)){
                for (Auth auth : authList) {
                    if (CrowdFundingUtils.stringEffective(auth.getName())){
                        authorityList.add(new SimpleGrantedAuthority(auth.getName()));
                    }
                }
            }

            return new SecurityAdmin(admin, authorityList);
        }else{
            return null;
        }
    }
}
